package me.pplay.playtalk.database;

import java.util.ArrayList;
import java.util.List;

import me.pplay.playtalk.bean.Chat;
import me.pplay.playtalk.data.Globals;
import me.pplay.playtalk.util.LogManager;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

public class FriendDb{
	private final String FRIEND_TBNAME	= "friend";
	private DbHelper dbHelper;
	public FriendDb(){}
	
	public FriendDb(Context context) {
		dbHelper	= new DbHelper(context);
	}

	/**
	 * 添加
	 * @return
	 */
	public boolean add(Chat chat){
		dbHelper.openDatabase();
		boolean bool = false;
		long result = 0;
		try{
			ContentValues values = new ContentValues();
			values.put("myskyid", chat.getMyskyid());
			values.put("skyid", chat.getSkyid());
			values.put("type", chat.getType());
			values.put("icon", chat.getIcon());
			values.put("name", chat.getName());
			values.put("message", chat.getMessage());
			values.put("time", chat.getTime());
			result = dbHelper.db.insert(FRIEND_TBNAME, null, values);
		}catch (Exception e) {
			LogManager.LogShow("FRIEND_TBNAME", e.getMessage());
		}finally{
			dbHelper.closeDatabase();
			if(result >0)
				bool = true;
		}
		return bool;
	}
	
	/**
	 * @param type 1:同意 2：拒绝  3 请求加好友  4好友状态（上下线）
	 * @return
	 */
	public List<Chat> queryList(int type){
		dbHelper.openDatabase();
		List<Chat> chatList		= new ArrayList<Chat>();
		Cursor cursor 			= null;
		try {
			String sql			= "select * from " + FRIEND_TBNAME + " where myskyid = "+ Globals.skyid + " and type=" + type +" order by time desc";
			cursor 				= dbHelper.db.rawQuery(sql, null);
			if(cursor != null){
				while (cursor.moveToNext()) {
					Chat chat	= new Chat();
					chat.set_id(cursor.getInt(cursor.getColumnIndex("_id")));
					chat.setType(cursor.getInt(cursor.getColumnIndex("type")));
					chat.setSkyid(cursor.getInt(cursor.getColumnIndex("skyid")));
					chat.setName(cursor.getString(cursor.getColumnIndex("name")));
					chat.setIcon(cursor.getString(cursor.getColumnIndex("icon")));
					chat.setMessage(cursor.getString(cursor.getColumnIndex("message")));
					chat.setTime(cursor.getString(cursor.getColumnIndex("time")));
					chatList.add(chat);
	            }
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null) {
				cursor.close();
			}
			dbHelper.closeDatabase();
		}
		return chatList;
	}
	
	/**
	 * 删除
	 */
	public void delete(int _id) {
		dbHelper.openDatabase();
		dbHelper.db.delete(FRIEND_TBNAME, "_id=" + _id + "", null);
		dbHelper.closeDatabase();
	}
}
